package com.gongpingjialoan.activity.main;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.sell.PhotoSelectorActivity;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.AuthBen;
import com.gongpingjialoan.bean.Monitor;
import com.gongpingjialoan.bean.PhotoModel;
import com.gongpingjialoan.constant.Const;
import com.gongpingjialoan.data.UserManager;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.network.UploadCallBack;
import com.gongpingjialoan.utility.PhotoUtil;
import com.gongpingjialoan.utility.PreferenceUtils;
import com.gongpingjialoan.utility.StepMonitor;
import com.gongpingjialoan.utility.UploadUtils;
import com.gongpingjialoan.view.GlideRoundTransform;
import com.tencent.mm.sdk.modelmsg.SendAuth;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.List;

/**
 * Created by Administrator on 2016/11/21.
 */
public class UserCenterActivity extends BaseActivity implements View.OnClickListener {

    private ImageView mImageView;

    private TextView phoneTextView, saveTextView;

    private EditText nickEditText;

    private View modifyView, weixinView;

    private UserManager mUserManager;

    private File dir;

    private static final int REQUEST_CROP = 7;

    private static final int REQUEST_FORGET = 88;

    private static final int REQUEST_IMG_TAKE = 8;

    private NetDataJson modifyNetDataJson, boundNetDataJson;

    private String uplaodUri = "", localPath = "";

    private String originalUri = "", originalName = "";

    private PopupWindow mPopupWindow;

    private View mGetPicLayout, mTakePicLayout;

    private ImageView mCloseLayoutImg;

    private String mPhotoPath;

    private boolean fromSetting = false;

    private TextView wxBindTextView , wxNoBindTextView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_center_layout);
        EventBus.getDefault().register(this);
        setTitle("个人中心");
        fromSetting = getIntent().getBooleanExtra("from_setting", false);
        dir = new File(this.getExternalCacheDir(), "gpj");
        if (!dir.exists()) dir.mkdirs();
        saveTextView = (TextView) findViewById(R.id.right);
        saveTextView.setText("保存");
        saveTextView.setVisibility(View.VISIBLE);
        mImageView = (ImageView) findViewById(R.id.image);
        phoneTextView = (TextView) findViewById(R.id.phone);
        nickEditText = (EditText) findViewById(R.id.nick);
        modifyView = findViewById(R.id.modify_psw);
        weixinView = findViewById(R.id.weixin);
        wxBindTextView = (TextView) findViewById(R.id.wx_bind);
        wxNoBindTextView = (TextView) findViewById(R.id.nobind);
        View view = LayoutInflater.from(this).inflate(R.layout.include_popup, null);
        view.findViewById(R.id.topview).setVisibility(View.GONE);
        mCloseLayoutImg = (ImageView) view
                .findViewById(R.id.imgView_close_layout);
        mGetPicLayout = view.findViewById(R.id.layout_get_pic);
        mTakePicLayout = view.findViewById(R.id.layout_take_pic);
        mCloseLayoutImg.setOnClickListener(this);
        mGetPicLayout.setOnClickListener(this);
        mTakePicLayout.setOnClickListener(this);
        mPopupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setAnimationStyle(R.style.PopupMenu);
        mPopupWindow.setFocusable(true);
        mPopupWindow.setOutsideTouchable(true);
        // 需要设置一下此参数，点击外边可消失
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());

        modifyView.setOnClickListener(this);
        mImageView.setOnClickListener(this);
        saveTextView.setOnClickListener(this);
        mUserManager = new UserManager().LoadUserInfo();
        if(!TextUtils.isEmpty(mUserManager.getWx_nickname())){
            wxBindTextView.setVisibility(View.VISIBLE);
            wxBindTextView.setText(mUserManager.getWx_nickname());
            wxNoBindTextView.setText("已绑定");
            findViewById(R.id.right_go).setVisibility(View.GONE);
        }else{
            weixinView.setOnClickListener(this);
        }
        phoneTextView.setText(mUserManager.getPhone());
        nickEditText.setText(mUserManager.getUser());
        originalName = mUserManager.getUser();
        if (!TextUtils.isEmpty(mUserManager.getAvatar())) {
            uplaodUri = mUserManager.getAvatar();
            originalUri = uplaodUri;
            Glide.with(this).load(mUserManager.getAvatar()).placeholder(R.drawable.user_img_icon).centerCrop().transform(new GlideRoundTransform(this)).into(mImageView);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refresh(Object o) {
        if (o instanceof AuthBen) {
            AuthBen authBen = (AuthBen) o;
            if (TextUtils.isEmpty(authBen.code)) {
                hidenProgressDialog();
                return;
            }
            boundWX(((AuthBen) o).code);
        }
    }

    /**
     * 微信登录
     */
    private void sendWxAuthRequest() {
        if (GPJApplication.getInstance().wxApi.isWXAppInstalled()) {
            showProgressDialog("加载中...");
            SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "gongpingjia_login";
            //拉起微信授权，授权结果在WXEntryActivity中接收处理
            GPJApplication.getInstance().wxApi.sendReq(req);
        } else {
            Toast.makeText(this, "请安装微信", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onClick(View v) {
        if (v == weixinView) {

             sendWxAuthRequest();
            //getMiCode();
        } else if (v == modifyView) {
            StepMonitor.getInstance().addMonitor(new Monitor("click", "my_modifyPassword", System.currentTimeMillis(), 1.0f));
            startActivityForResult(new Intent(this, ForgetPswActivity.class), REQUEST_FORGET);
        } else if (v == saveTextView) {
            save();
        } else if (v == mImageView) {
            mPopupWindow.showAtLocation(mImageView, Gravity.BOTTOM, 0, 0);
        } else if (v == mGetPicLayout) {
            mPopupWindow.dismiss();
            Intent intent = new Intent(this,
                    PhotoSelectorActivity.class);
            intent.putExtra(PhotoSelectorActivity.KEY_MAX,
                    1);
            intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
            startActivityForResult(intent, Const.PICK_PHOTO);
        } else if (v == mTakePicLayout) {
            mPopupWindow.dismiss();
            mPhotoPath = new File(dir, System.currentTimeMillis() + ".jpg")
                    .getAbsolutePath();
            PhotoUtil.getPhotoFromCamera(this, REQUEST_IMG_TAKE, mPhotoPath);
        }
    }

    @Override
    public void initTitleBar() {
        View backV = findViewById(R.id.title_back);
        if (backV != null) {
            backV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    onBackPressed();
                }
            });
        }
    }


    @Override
    public void onBackPressed() {
        if (!originalName.equals(nickEditText.getText().toString()) || !originalUri.equals(uplaodUri)) {
            AlertDialog.Builder ad = new AlertDialog.Builder(this);
            ad.setTitle("提示");
            ad.setMessage("您有修改未做保留，是否返回？");
            ad.setPositiveButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
            ad.setNegativeButton("仍然返回", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
            ad.create().show();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_FORGET) {
                if (!fromSetting) {
                    startActivity(new Intent(this, LoginActivity.class));
                    finish();
                } else {
                    setResult(Activity.RESULT_OK);
                    finish();
                }
            } else if (requestCode == Const.PICK_PHOTO) {
                showProgressDialog("图片上传中...");
                if (data != null && data.getExtras() != null) {
                    List<PhotoModel> photos = (List<PhotoModel>) data.getExtras().getSerializable("photos");
                    if (photos == null || photos.isEmpty()) {
                        Toast.makeText(this, "没有选择图片!", Toast.LENGTH_SHORT).show();
                        hidenProgressDialog();
                    } else {
                        String newPhotoPath = new File(dir, System.currentTimeMillis() + ".jpg")
                                .getAbsolutePath();
                        Bitmap btp = PhotoUtil.getLocalImage(new File(photos.get(0).getOriginalPath()));
                        localPath = newPhotoPath;
                        PhotoUtil.saveLocalImageSquare(btp, new File(newPhotoPath));
                        uploadImg(newPhotoPath);
                    }
                }
            } else if (requestCode == REQUEST_IMG_TAKE) {
                PhotoUtil.onPhotoFromCamera(this, REQUEST_CROP, mPhotoPath, 3,
                        2, 2000);
            } else if (requestCode == REQUEST_CROP) {
                showProgressDialog("图片上传中...");
                localPath = mPhotoPath;
                uploadImg(mPhotoPath);
            }
        }
    }

    private void uploadImg(String path) {
        UploadUtils.uploadImage(path, new UploadCallBack() {
            @Override
            public void success(String uri) {
                uplaodUri = uri;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        hidenProgressDialog();
                        Glide.with(UserCenterActivity.this).load(localPath).transform(new GlideRoundTransform(UserCenterActivity.this)).into(mImageView);
                    }
                });

            }

            @Override
            public void failure() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        hidenProgressDialog();
                        Toast.makeText(UserCenterActivity.this, "上传图片失败, 请重试", Toast.LENGTH_SHORT).show();

                    }
                });
            }
        }, API.uploadPic, "avatar");
    }


    private void save() {
        if (TextUtils.isEmpty(nickEditText.getText().toString())) {
            Toast.makeText(this, "请输入昵称", Toast.LENGTH_SHORT).show();
            return;
        }
        showProgressDialog("保存中...");
        if (modifyNetDataJson == null) {
            modifyNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                    hidenProgressDialog();
                    Toast.makeText(UserCenterActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onDataJsonUpdate(JSONObject json) {
                    hidenProgressDialog();
                    originalUri = uplaodUri;
                    originalName = nickEditText.getText().toString();
                    mUserManager.setAvatar(uplaodUri);
                    mUserManager.setUser(nickEditText.getText().toString());
                    PreferenceUtils mPreferenceUtils = new PreferenceUtils(UserCenterActivity.this);
                    mPreferenceUtils.saveObject(mUserManager);
                    if (MainActivity.main != null) {
                        if (MainActivity.main.mUserHomeFragment != null && MainActivity.main.mUserHomeFragment.isAdded()) {
                            MainActivity.main.mUserHomeFragment.refresh();
                        }
                    }
                    Toast.makeText(UserCenterActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                }
            });
        }
        modifyNetDataJson.setUrl("/mobile/account/post-update-user-profile/");
        modifyNetDataJson.addParam("contact", nickEditText.getText().toString());
        modifyNetDataJson.addParam("avatar", uplaodUri);
        modifyNetDataJson.request("post");
    }

    private void boundWX(String code) {
        if (boundNetDataJson == null) {
            boundNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                    hidenProgressDialog();
                    Toast.makeText(UserCenterActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onDataJsonUpdate(JSONObject json) {
                    hidenProgressDialog();
                    Toast.makeText(UserCenterActivity.this, "绑定成功", Toast.LENGTH_SHORT).show();
                    wxBindTextView.setVisibility(View.VISIBLE);
                    String name = "";
                    try {
                        name =  json.getJSONObject("data").getJSONObject("wechat_user").getString("nickname");
                    } catch (JSONException e) {
                    }
                    wxBindTextView.setText(name);
                    wxNoBindTextView.setText("已绑定");
                    mUserManager.setWx_nickname(name);
                    mUserManager.SaveUserInfo(mUserManager);
                    findViewById(R.id.right_go).setVisibility(View.GONE);
                    weixinView.setOnClickListener(null);
                }
            });
        }
        boundNetDataJson.addParam("code", code);
        boundNetDataJson.setUrl("/mobile/account/wechat-bind/");
        boundNetDataJson.request("post");
    }
}
